package com.woyou.ui.activity;

import java.util.ArrayList;
import java.util.List;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.citaq.ideliver.R;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.FmInfoBean;
import com.woyou.bean.MyAddress;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.ManagerAddrReq;
import com.woyou.ui.api.IBackEventStrategy;
import com.woyou.ui.component.EditDialog;
import com.woyou.ui.component.EditDialog.BtnListener;
import com.woyou.utils.CharCheckUtil;
import com.woyou.utils.Dialog;
import com.woyou.utils.LogUtil;
import com.woyou.utils.eventbus.EventRefreshAddrList;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import de.greenrobot.event.EventBus;
import retrofit.RetrofitError;

/**
 * 新增配送地址PutAddrFragment
 * 
 * @author tanglc
 */
@EActivity(R.layout.fm_putaddr)
public class PutAddrActivity extends BaseActivity implements IBackEventStrategy {

	private MyAddress newAddr;
	Dialog dialog = new Dialog();
	EditDialog editDialog = new EditDialog();

	ManagerAddrReq managerAddrReq;
	CodeListResult<MyAddress> result;
	private MyLocationListener mListener;
	protected ProgressDialog progress;

	@ViewById
	// 头部返回按钮
	RelativeLayout myback;
	@ViewById
	// 头部标题
	TextView head_title, deletetext;
	@ViewById
	// 录入姓名、录入地址、录入手机号
	EditText putaddr_name, putaddr_addr, addrphone;
	@ViewById
	// 定位按钮、头部提交按钮、单选男、单选女、删除姓名、删除地址、删除手机号、删除该地址
	LinearLayout putaddr_latlngbtn, submitbtn, putaddr_nan, putaddr_nv, putaddr_namedle, putaddr_latlngdle,
			putaddr_phonedle, putaddr_delete;
	@ViewById
	// 性别：男、女
	RadioButton sexnan_radiobtn, sexnv_radioButton;

	private String lng = "0.00000000";
	private String lat = "0.00000000";

	protected ProgressDialog locationProgress;

	@AfterViews
	public void init() {
		initView();
		progress = getProgressDialog("正在加载,请稍后...");
		progress.setCancelable(false);
		// 删除该条地址
		editDialog.setBtnListener(new BtnListener() {
			@Override
			public void pressBtn(int id, String str) {
				switch (id) {
				case R.id.ok_button:
					if (str.equals("putaddr_delete")) {
						deleteView();
					} else if (str.equals("putaddr_back")) {
						// clazz = PutAddrFragment_.class;
						// BusProvider.getInstance().post(DestoryFM());
						finish();
					}
					break;
				default:
					break;
				}
			}
		});
	}

	// public void onHiddenChanged(boolean hidden) {
	// // 初始化数据
	// if (!hidden) {
	// init();
	// } else {
	// dialog.dismiss();
	// editDialog.dismiss();
	// }
	// };

	@Override
	public void onResume() {
		super.onResume();
		init();
	}

	@Override
	public void onPause() {
		super.onPause();
		dialog.dismiss();
		editDialog.dismiss();
	}

	@Click({ R.id.myback, R.id.submitbtn, R.id.putaddr_latlngbtn, R.id.cancle_button, R.id.ok_button, R.id.putaddr_nan,
			R.id.putaddr_nv, R.id.putaddr_namedle, R.id.putaddr_latlngdle, R.id.putaddr_phonedle, R.id.putaddr_delete })
	void loginOnClick(View view) {
		switch (view.getId()) {
		case R.id.myback:
			// 退出新增地址界面
			backOperate();
			break;
		case R.id.submitbtn:
			// 提交用户新增地址信息
			hideSoftInput(mContext, putaddr_name);
			if (checkParams()) {
				submitView();
			}
			break;
		case R.id.putaddr_latlngbtn:
			showLocationDialog();
			mListener = new MyLocationListener();
			mBaiduLocationService.registerLocationListenner(mListener);
			// 点击定位按钮
			mBaiduLocationService.startLocation();
			hideSoftInput(mContext, putaddr_name);
			break;
		case R.id.putaddr_nan:
			// 选择先生按钮
			setCheck(sexnan_radiobtn, sexnv_radioButton);
			hideSoftInput(mContext, putaddr_name);
			break;
		case R.id.putaddr_nv:
			// 选择女士按钮
			setCheck(sexnv_radioButton, sexnan_radiobtn);
			hideSoftInput(mContext, putaddr_name);
			break;
		case R.id.putaddr_namedle:
			// 清空姓名
			putaddr_name.setText("");
			break;
		case R.id.putaddr_latlngdle:
			// 清空地址
			putaddr_addr.setText("");
			break;
		case R.id.putaddr_phonedle:
			// 清空手机号码
			addrphone.setText("");
			break;
		case R.id.putaddr_delete:
			// 删除该条记录
			editDialog.Dialog(mContext, deletetext, R.id.deletetext, "您是否要删除该条记录？", "isDialog");
			// deleteView();
			break;
		default:
			break;
		}
	}

	public void setCheck(RadioButton truebtn, RadioButton flasebtn) {
		truebtn.setChecked(true);
		truebtn.setBackgroundResource(R.raw.rediobox1);
		flasebtn.setChecked(false);
		flasebtn.setBackgroundResource(R.raw.rediobox2);
	}

	/**
	 * 初始化数据 tanglc
	 */
	public void initView() {
		head_title.setText("新增配送地址");
		sexnan_radiobtn.setBackgroundResource(R.raw.rediobox2);
		sexnan_radiobtn.setChecked(false);
		sexnv_radioButton.setBackgroundResource(R.raw.rediobox2);
		sexnv_radioButton.setChecked(false);
		if (getInfoBean() != null && !getInfoBean().equals("")
				&& !getInfoBean().getData().equals("ConfirmOrderFragment")) {
			// 修改地址页面初始化
			head_title.setText("管理配送地址");
			updateInitView();
		} else {
			// 新增地址页面初始化
			addInitView();
		}
		putaddr_name.addTextChangedListener(new NameEditChangedListener());
		putaddr_addr.addTextChangedListener(new AddrEditChangedListener());
		addrphone.addTextChangedListener(new phoneEditChangedListener());
		submitbtn.setVisibility(View.VISIBLE);
	}

	/**
	 * 修改地址页面初始化 tanglc 上午11:22:48
	 */
	public void updateInitView() {
		newAddr = (MyAddress) getInfoBean().getData();
		putaddr_name.setTextColor(Color.BLACK);
		putaddr_addr.setTextColor(Color.BLACK);
		addrphone.setTextColor(Color.BLACK);
		putaddr_name.setText(newAddr.getContact());
		if (newAddr.getSex() == 2) {
			setCheck(sexnan_radiobtn, sexnv_radioButton);
		} else if (newAddr.getSex() == 1) {
			setCheck(sexnv_radioButton, sexnan_radiobtn);
		}
		addrphone.setText(newAddr.getPhone());
		putaddr_addr.setText(newAddr.getAddrName());
		putaddr_latlngbtn.setVisibility(View.GONE);
		putaddr_namedle.setVisibility(View.VISIBLE);
		putaddr_latlngdle.setVisibility(View.VISIBLE);
		putaddr_phonedle.setVisibility(View.VISIBLE);
		putaddr_delete.setVisibility(View.VISIBLE);
	}

	/**
	 * 新增地址页面初始化 tanglc 上午11:23:03
	 */
	public void addInitView() {
		UserInfo userInfo = mUserModel.getUserInfo();
		if (userInfo.getName() != null && !userInfo.getName().equals("") && userInfo.getName().length() <= 10) {
			putaddr_name.setText(userInfo.getName());
			putaddr_namedle.setVisibility(View.VISIBLE);
		} else {
			putaddr_name.setText("");
			putaddr_namedle.setVisibility(View.GONE);
		}
		if (userInfo.getPhone() != null && !userInfo.getPhone().equalsIgnoreCase("")) {
			addrphone.setText(userInfo.getPhone());
			putaddr_phonedle.setVisibility(View.VISIBLE);
		} else {
			addrphone.setText("");
			putaddr_phonedle.setVisibility(View.GONE);
		}
		putaddr_addr.setText("");
		putaddr_name.setTextColor(Color.GRAY);
		putaddr_addr.setTextColor(Color.GRAY);
		addrphone.setTextColor(Color.GRAY);
		putaddr_latlngbtn.setVisibility(View.VISIBLE);
		putaddr_latlngdle.setVisibility(View.GONE);
		putaddr_delete.setVisibility(View.GONE);
	}

	/**
	 * 点击删除按钮删除该条地址信息
	 * 
	 * @author tanglc
	 */
	public void deleteView() {
		progress.show();
		// 删除地址设置请求参数
		setDeleteParam();
		// 向服务器请求并获得数据
		getResult();
	}

	/**
	 * 删除设置请求参数 tanglc
	 */
	public void setDeleteParam() {
		try {
			ArrayList<MyAddress> myaddrList = new ArrayList<MyAddress>();
			myaddrList.addAll(mUserModel.queryAddrList());
			for (int i = 0; i < myaddrList.size(); i++) {
				if (myaddrList.get(i).getAddrId().equals(newAddr.getAddrId())) {
					myaddrList.get(i).setState(2);
				}
			}
			managerAddrReq = new ManagerAddrReq();
			managerAddrReq.setUid(mUserModel.getUserInfo().getuId());
			managerAddrReq.setPwd(mUserModel.getUserInfo().getPwd());
			managerAddrReq.setList(myaddrList);
		} catch (Exception e) {
			progress.dismiss();
			showToast("参数异常");
		}
	}

	/**
	 * 点击保存按钮提交用户地址信息
	 * 
	 * @author tanglc
	 */
	public void submitView() {
		progress.show();
		// 新增或修改设置请求参数
		setParam();
		// 向服务器请求并获得数据
		getResult();
	}

	/**
	 * 新增或修改设置请求参数 tanglc
	 */
	public void setParam() {
		try {
			ArrayList<MyAddress> myaddrList = new ArrayList<MyAddress>();
			if (getInfoBean() != null && getInfoBean().getData() != null
					&& !getInfoBean().getData().equals("ConfirmOrderFragment")) {
				// 修改地址
				List<MyAddress> addrList = new ArrayList<MyAddress>();
				if (mUserModel.queryAddrList() != null && mUserModel.queryAddrList().size() > 0) {
					addrList.addAll(mUserModel.queryAddrList());
				}
				for (int i = 0; i < addrList.size(); i++) {
					if (addrList.get(i).getAddrId().equals(newAddr.getAddrId())) {
						addrList.get(i).setAddrId(addrList.get(i).getAddrId()); // 待定
						addrList.get(i).setContact(putaddr_name.getText().toString());
						if (sexnan_radiobtn.isChecked()) {
							addrList.get(i).setSex(2);
						} else if (sexnv_radioButton.isChecked()) {
							addrList.get(i).setSex(1);
						} else {
							addrList.get(i).setSex(0);
						}
						addrList.get(i).setPhone(addrphone.getText().toString());
						addrList.get(i).setAddrName(putaddr_addr.getText().toString());
						addrList.get(i).setCityCode(addrList.get(i).getCityCode()); // city.setcitycode()
						addrList.get(i).setCityName(addrList.get(i).getCityName()); // city.setcityname()
						addrList.get(i).setLat(addrList.get(i).getLat());
						addrList.get(i).setLng(addrList.get(i).getLng());
						addrList.get(i).setState(3);
					}
					myaddrList.add(addrList.get(i));
				}
			} else {
				// 新增地址
				newAddr = new MyAddress();
				newAddr.setContact(putaddr_name.getText().toString());
				if (sexnan_radiobtn.isChecked()) {
					newAddr.setSex(2);
				} else if (sexnv_radioButton.isChecked()) {
					newAddr.setSex(1);
				} else {
					newAddr.setSex(0);
				}
				newAddr.setPhone(addrphone.getText().toString());
				newAddr.setAddrName(putaddr_addr.getText().toString());
				newAddr.setCityCode(""); // city.setcitycode()
				newAddr.setCityName(""); // city.setcityname()
				newAddr.setLat(lat);
				newAddr.setLng(lng);
				newAddr.setState(1);
				if (mUserModel.queryAddrList() != null && mUserModel.queryAddrList().size() > 0) {
					myaddrList.addAll(mUserModel.queryAddrList());
				}
				myaddrList.add(newAddr);
				LogUtil.d("newAddr", newAddr.toString());
			}
			managerAddrReq = new ManagerAddrReq();
			managerAddrReq.setUid(mUserModel.getUserInfo().getuId());
			managerAddrReq.setPwd(mUserModel.getUserInfo().getPwd());
			managerAddrReq.setList(myaddrList);
		} catch (RetrofitError e) {
			progress.dismiss();
			switch (e.getKind()) {
			case CONVERSION:
				return;
			case HTTP:
				return;
			case NETWORK:
				return;
			case UNEXPECTED:
				return;
			}
		}
	}

	/**
	 * 请求服务器 tanglc
	 * 
	 * @return
	 */
	FmInfoBean fmInfoBean = null;

	@Background
	public void getResult() {
		try {
			// 判断是否已登录，登录则请求服务器，否则将数据保存在本地
			if (!mUserModel.getUserInfo().getuId().equals("")) {
				result = mUserModel.managerAddr(managerAddrReq);
				showView();
			} else {
				List<MyAddress> list = new ArrayList<MyAddress>();
				MyAddress myaddr = new MyAddress();
				myaddr.setContact(putaddr_name.getText().toString());
				if (sexnan_radiobtn.isChecked()) {
					myaddr.setSex(2);
				} else if (sexnv_radioButton.isChecked()) {
					myaddr.setSex(1);
				} else {
					myaddr.setSex(0);
				}
				myaddr.setPhone(addrphone.getText().toString());
				myaddr.setAddrName(putaddr_addr.getText().toString());
				myaddr.setState(1);
				list.add(myaddr);
				mUserModel.saveAddrList(list);
				fmInfoBean = new FmInfoBean(myaddr, PutAddrActivity_.class);
				// clazz = PutAddrFragment_.class;
				// BusProvider.getInstance().post(DestoryFM());
				finish();
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case CONVERSION:
				return;
			case HTTP:
				return;
			case NETWORK:
				showToast("网络异常，请检查您的网络是否已开启!");
				return;
			case UNEXPECTED:
				return;
			}
		} finally {
			progress.dismiss();
		}
	}

	@UiThread
	public void showView() {
		if (result != null && result.code == 1) {
			showToast(result.msg);
			List<MyAddress> myaddrList = mUserModel.queryAddrList();
			if (myaddrList.size() == 1) {
				fmInfoBean = new FmInfoBean(myaddrList.get(0), PutAddrActivity_.class);
			}
			// clazz = PutAddrFragment_.class;
			// BusProvider.getInstance().post(DestoryFM());
			finish();
			EventBus.getDefault().post(new EventRefreshAddrList());
		} else if (result != null && result.code == -3) {
			// clazz = MyAddrFragment_.class;
			// BusProvider.getInstance().post(DestoryFM());
			// clazz = PutAddrFragment_.class;
			// BusProvider.getInstance().post(DestoryFM());
			finish();
			dialog.LoginToast(mContext, result.msg);
		} else {
			showToast(result.msg);
		}
	}

	/**
	 * 关闭Fragment
	 * 
	 * @author tanglc
	 */
	// @Produce
	// public EventCloseFM<Class, FmInfoBean<MyAddress>> closeFmInfoBeanFM() {
	// return new EventCloseFM(clazz, fmInfoBean);
	// }

	// /**
	// * 关闭当前Fragment
	// *
	// * @author tanglc
	// */
	// @Produce
	// public EventCloseFM closeFM() {
	// return new EventCloseFM(clazz);
	// }

	// /**
	// * 销毁Fragment
	// *
	// * @author tanglc
	// */
	// @Produce
	// public EventCloseFM<Class, FmInfoBean<MyAddress>> DestoryFM() {
	// EventCloseFM closeFM = new EventCloseFM(clazz, fmInfoBean);
	// closeFM.setDestory(true);
	// BusProvider.getInstance().unregister(this);
	// return closeFM;
	// }
	//
	// /**
	// * 打开Fragment
	// *
	// * @author tanglc
	// */
	// @Produce
	// public EventOpenFM<Class, FmInfoBean> openFM() {
	// return new EventOpenFM<Class, FmInfoBean>(clazz, null);
	// }

	private String lastAddr = null;

	/**
	 * 接收事件:定位成功
	 * 
	 * @author tanglc
	 * 
	 */
	class MyLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			mBaiduLocationService.stop();
			dismissLocationDialog();
			mBaiduLocationService.unRegisterLocationListener(mListener);
			mListener = null;
			lastAddr = location.getAddrStr();
			if (location != null) {
				lat = String.valueOf(location.getLatitude()); // 用户纬度
				lng = String.valueOf(location.getLongitude()); // 用户经度
				if (!TextUtils.isEmpty(lastAddr)) {
					putaddr_addr.setText(lastAddr);
					showToast("定位成功");
				} else {
					putaddr_addr.setText("定位失败");
					showToast("定位失败，请重新定位!");
				}

			}
		}
	}

	void showLocationDialog() {
		runOnUI(new Runnable() {

			@Override
			public void run() {
				try {
					if (locationProgress == null) {
						locationProgress = new ProgressDialog(mContext);
						locationProgress.setMessage("正在定位,请稍后...");
						locationProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					}
					locationProgress.setCancelable(true);
					locationProgress.show();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	void dismissLocationDialog() {
		runOnUI(new Runnable() {
			@Override
			public void run() {
				if (locationProgress != null) {
					locationProgress.dismiss();
				}
			}
		});
	}

	public boolean checkParams() {
		if (putaddr_name.getText().toString().equals("")) {
			showToast("请输入姓名!");
			return false;
		}
		if (!CharCheckUtil.CheckStrType(putaddr_name.getText().toString())) {
			showToast("您录入的联系人姓名有误，请重新录入!");
			return false;
		}
		if (putaddr_addr.getText().toString().equals("") || putaddr_addr.getText().toString().split(" ").length == 0) {
			showToast("地址不能为空或者全部为空格");
			return false;
		}
		if (addrphone.getText().toString().equals("")) {
			showToast("请输入手机号!");
			return false;
		}
		if (!CharCheckUtil.isPhoneNum(addrphone.getText().toString())) {
			showToast("您录入的手机号码有误，请重新录入!");
			return false;
		}
		return true;
	}

	/**
	 * 姓名监听
	 * 
	 * @author shenzhou 2015年1月9日
	 */
	class NameEditChangedListener implements TextWatcher {
		private String temp;
		private boolean flag = false;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (flag) {
				return;
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			if (flag) {
				return;
			}
			temp = s.toString();
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (flag) {
				flag = false;
				return;
			}
			if (putaddr_name.getText().toString().length() > 10) {
				showToast("不要输入太长的名字喔");
				flag = true;
				putaddr_name.setText(temp);
				putaddr_name.setSelection(temp.length());
			}
			if (putaddr_name.getText().toString().length() == 0) {
				putaddr_namedle.setVisibility(View.GONE);
			} else {
				putaddr_namedle.setVisibility(View.VISIBLE);
			}
		}
	}

	/**
	 * 地址监听
	 * 
	 * @author shenzhou 2015年1月9日
	 */
	class AddrEditChangedListener implements TextWatcher {
		private String temp;
		private boolean flag = false;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (flag) {
				return;
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			if (flag) {
				return;
			}
			temp = s.toString();
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (flag) {
				flag = false;
				return;
			}
			if (!CharCheckUtil.allowMaxLenthOfString(putaddr_addr.getText().toString(), 200)) {
				showToast("不要输入太长的地址喔");
				flag = true;
				putaddr_addr.setText(temp);
				putaddr_addr.setSelection(temp.length());
			}
			if (putaddr_addr.getText().toString().length() > 0) {
				putaddr_latlngdle.setVisibility(View.VISIBLE);
				putaddr_latlngbtn.setVisibility(View.GONE);
			} else {
				putaddr_latlngdle.setVisibility(View.GONE);
				putaddr_latlngbtn.setVisibility(View.VISIBLE);
			}
		}
	}

	/**
	 * 手机监听
	 * 
	 * @author shenzhou 2015年1月9日
	 */
	class phoneEditChangedListener implements TextWatcher {
		private String temp;
		private boolean flag = false;

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			if (flag) {
				return;
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			if (flag) {
				return;
			}
			temp = s.toString();
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if (flag) {
				flag = false;
				return;
			}
			if (addrphone.getText().toString().length() > 11) {
				showToast("不要输入太长的手机号喔");
				flag = true;
				addrphone.setText(temp);
				addrphone.setSelection(temp.length());
			}
			if (addrphone.getText().toString().length() == 0) {
				putaddr_phonedle.setVisibility(View.GONE);
			} else {
				putaddr_phonedle.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	public boolean backOperate() {
		// TODO Auto-generated method stub
		hideSoftInput(mContext, putaddr_name);
		if (!putaddr_name.getText().toString().equals("") || !putaddr_addr.getText().toString().equals("")
				|| !addrphone.getText().toString().equals("") || sexnan_radiobtn.isChecked()
				|| sexnv_radioButton.isChecked()) {
			editDialog.Dialog(mContext, head_title, R.id.head_title, "是否放弃编辑？", "isDialog");
		} else {
			// clazz = PutAddrFragment_.class;
			// BusProvider.getInstance().post(DestoryFM());
			finish();
			hideSoftInput(mContext, putaddr_name);
		}
		return true;
	}
}
